<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { ElMessageBox } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import HeaderKnownFaultList from './Header.vue'
  import FaultCreateModal from './FaultCreateModal.vue'
  import TypesKnownFaults from './Type.vue'
  import {
    useFaultsDel,
    useFaultsEnable,
    useFaultsDisable,
    useFaultsMobileShow,
    useFaultsMobileHide,
    useFaultsReportAnalysisEnable,
    useFaultsReportAnalysisDisable,
  } from '@/services/pages/know/fault'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import Table from './Table.vue'

  const { faultsEnable } = useFaultsEnable()
  const { deleteFaults } = useFaultsDel()
  const { faultsDisable } = useFaultsDisable()
  const { faultMobileShow } = useFaultsMobileShow()
  const { faultMobileHide } = useFaultsMobileHide()
  const { enableReportAnalysis } = useFaultsReportAnalysisEnable()
  const { disableReportAnalysis } = useFaultsReportAnalysisDisable()

  defineOptions({
    name: 'FaultsKnow',
  })

  // 表格组件实例
  const tableInstance = ref<InstanceType<typeof Table> | null>(null)
  const typesKnowFaultsInstance = ref<InstanceType<typeof TypesKnownFaults> | null>(null)
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const knownFaultAddDialogVisible = ref(false)

  // 正在编辑的故障库的id
  const currentEditFaultId = ref('')

  // 故障库id选择列表
  const selectedFaultIds = ref<Array<string>>([])

  // 列表总条数
  const listTotal = computed(() => {
    if (tableInstance.value) {
      return tableInstance.value.total
    }
    return 0
  })

  // 搜索表单
  const searchForm = ref({
    faultReason: '',
    name: '',
    oneFaultTypeId: '',
    solution: '',
    threeFaultTypeId: '',
    twoFaultTypeId: '',
  })

  // 表头组件实例
  const headerInstance = ref<InstanceType<typeof HeaderKnownFaultList> | null>(null)

  /**
   * 选择故障库事件
   * @param {Array<string>} selection - 故障库id选择列表
   */
  const handleSelectionChange = (selection: Array<string>) => {
    selectedFaultIds.value = selection
  }

  /**
   * 获取故障库列表
   */
  const getList = async () => {
    if (paginationInstance.value && tableInstance.value) {
      tableInstance.value.getList({
        limit: paginationInstance.value.size,
        name: searchForm.value.name,
        page: paginationInstance.value.current,
        solution: searchForm.value.solution,
        faultReason: searchForm.value.faultReason,
        oneFaultTypeId: searchForm.value.oneFaultTypeId,
      })
    }
  }

  /**
   * 添加故障库事件
   */
  const addFault = async () => {
    knownFaultAddDialogVisible.value = true
    currentEditFaultId.value = ''
  }

  /**
   * 批量操作
   * @param {'del' | 'enable' | 'disable' | 'mobileShow' | 'mobileHide' | 'enableReportAnalysis' | 'disableReportAnalysis'} type - 操作类型
   */
  const multipleMethod = (
    type:
      | 'del'
      | 'enable'
      | 'disable'
      | 'mobileShow'
      | 'mobileHide'
      | 'enableReportAnalysis'
      | 'disableReportAnalysis',
  ) => {
    if (selectedFaultIds.value.length <= 0) {
      HMessageBox.error('请选择故障')
      return
    }
    const typeOptions = {
      del: infoTip.know.fault.list.multipleDel,
      enable: infoTip.know.fault.list.multipleEnable,
      disable: infoTip.know.fault.list.multipleDisable,
      mobileShow: infoTip.know.fault.list.multipleMobileShow,
      mobileHide: infoTip.know.fault.list.multipleMobleHide,
      enableReportAnalysis: infoTip.know.fault.list.multipleEnbaleReportAnalysis,
      disableReportAnalysis: infoTip.know.fault.list.multipleDisableReportAnalysis,
    }
    ElMessageBox({
      title: '提示',
      message: typeOptions[type],
      type: type === 'del' ? 'error' : 'warning',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
        }

        if (action === 'confirm') {
          let res: null | APIResponse = null
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          switch (type) {
            case 'del':
              res = await deleteFaults(selectedFaultIds.value)
              break
            case 'disable':
              res = await faultsDisable(selectedFaultIds.value)
              break
            case 'enable':
              res = await faultsEnable(selectedFaultIds.value)
              break
            case 'mobileShow':
              res = await faultMobileShow(selectedFaultIds.value)
              break
            case 'mobileHide':
              res = await faultMobileHide(selectedFaultIds.value)
              break
            case 'enableReportAnalysis':
              res = await enableReportAnalysis(selectedFaultIds.value)
              break
            case 'disableReportAnalysis':
              res = await disableReportAnalysis(selectedFaultIds.value)
              break
          }
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false

          if (res && res.code === 20000) {
            const successMessageOption = {
              del: infoTip.know.fault.list.delSuccess,
              disable: infoTip.know.fault.list.disableSuccess,
              enable: infoTip.know.fault.list.enableSuccess,
              mobileShow: infoTip.know.fault.list.updateMobileStatusSuccess,
              mobileHide: infoTip.know.fault.list.updateMobileStatusSuccess,
              enableReportAnalysis: infoTip.know.fault.list.updateReportAnalysisStatusSuccess,
              disableReportAnalysis: infoTip.know.fault.list.updateReportAnalysisStatusSuccess,
            }
            HMessage.success(successMessageOption[type])
            done()
            getList()
            return
          }
          HMessageBox.error(res.message)
        }
      },
    })
  }

  /**
   * 表头搜索事件
   * @param {String} _searchForm - 搜索表单
   */
  const handleSearch = (_searchForm: {
    faultReason: string
    name: string
    oneFaultTypeId: string
    solution: string
    threeFaultTypeId: string
    twoFaultTypeId: string
  }) => {
    searchForm.value = _searchForm
    getList()
  }

  /**
   * 分类更新事件
   * @param {String} typeId - 分类id
   */
  const handleTypeChange = (typeId: string) => {
    if (headerInstance.value) {
      headerInstance.value.reset()
    }
    searchForm.value.oneFaultTypeId = typeId
    getList()
  }

  defineExpose({
    getList,
    getFaultTypes: () => {
      if (typesKnowFaultsInstance.value) {
        typesKnowFaultsInstance.value.getFaultTypes()
      }
    },
  })
</script>

<template>
  <div class="known-faults-wrapper">
    <div class="types">
      <types-known-faults
        ref="typesKnowFaultsInstance"
        @update-list="handleTypeChange"
      ></types-known-faults>
    </div>
    <div class="divider"></div>
    <div class="faults-known">
      <header-known-fault-list
        ref="headerInstance"
        :selected-fault-ids="selectedFaultIds"
        @add="addFault"
        @multiple-enable="multipleMethod('enable')"
        @multiple-disable="multipleMethod('disable')"
        @multiple-del="multipleMethod('del')"
        @multiple-mobile-show="multipleMethod('mobileShow')"
        @multiple-mobile-hide="multipleMethod('mobileHide')"
        @multiple-disable-report-analysis="multipleMethod('disableReportAnalysis')"
        @multiple-enable-report-analysis="multipleMethod('enableReportAnalysis')"
        @search="handleSearch"
      ></header-known-fault-list>

      <!-- 表格内容 -->
      <div class="table">
        <Table ref="tableInstance" @selection-change="handleSelectionChange"></Table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginationInstance"
          :list_total="listTotal"
          @size-change="getList"
          @current-change="getList"
        />
      </div>

      <fault-create-modal v-model:visible="knownFaultAddDialogVisible" @search="getList" />
    </div>
  </div>
</template>

<style scoped lang="scss">
  @import './index.scss';
</style>
